var app = getApp(),
  common = require("../../common/common.js"),
  WxParse = require('../../../../wxParse/wxParse.js')

// 答题结果
// var selected_all = [] //全部答案 对错 展示
// var all_answer_id = []
// var selected_true = [] //统计正确答案个数
// var selected_false = [] //统计错误答案个数

Page({
  data: {
    listData: [],
    options: 0,
    selected_all: [], //全部答案 对错 展示
    all_answer_id: [],
    selected_true: [], //统计正确答案个数
    selected_false: [], //统计错误答案个数
  },
  // 题
  current(e) {
    console.log(e.detail.current)
    let _t = this
    _t.setData({
      options: e.detail.current
    })
  },
  // 选择选项
  chooseOptions(t) {
    let _t = this
    // 选项
    let selected = t.currentTarget.dataset.index
    // 当前题目 号码
    let optionsNow = _t.data.options
    _t.data.test[optionsNow].answer_option[selected].active = !_t.data.test[optionsNow].answer_option[selected].active
    _t.setData({
      test: _t.data.test
    })
  },
  // 禁止 sw-item 滑动
  stopTouchMove() {
    return false;
  },
  // 下一题
  nextPage(e) {
    let _t = this
    console.log(e)
    let index = e.currentTarget.dataset.index
    let correct = e.currentTarget.dataset.correct
    let len = e.currentTarget.dataset.len
    _t.data.options++
      // 如果是最后一题  则直接跳转新的页面
      if (_t.data.options == len) {
        _t.endTheTest()
      }
    _t.setData({
      options: _t.data.options
    })
  },
  // 下一题
  nextOptions(e) {
    let _t = this
    console.log(e)
    let index = e.currentTarget.dataset.index
    let correct = e.currentTarget.dataset.correct
    let len = e.currentTarget.dataset.len
    // 判断对错
    _t.theMoreJudge(_t, index, correct)
    _t.data.options++
      // 如果是最后一题  则直接跳转新的页面
      if (_t.data.options == len) {
        _t.endTheTest()
      }
    _t.setData({
      options: _t.data.options
    })
  },


  // 判断当前
  theMoreJudge(_t, index, correct) {

    console.log(_t.data.selected_all + '//全部答案 对错 展示')
    console.log(_t.data.all_answer_id + '//全部答案 的 id')
    console.log(_t.data.selected_true + '//统计正确答案个数')
    console.log(_t.data.selected_false + '//统计错误答案个数')
    console.log('====================================================判断当前')

    let answer_option = _t.data.test[index].answer_option
    let more_sure = _t.data.test[index].correct.join(',')
    // 多选
    let multi_select = []
    for (let k = 0; k < answer_option.length; k++) {
      if (answer_option[k].active == true) {
        multi_select.push(k + 1)
      }
    }
    multi_select = multi_select.join(',')

    console.log(multi_select)
    console.log(more_sure)
    console.log("===================================================multi_select")
    // 数组转字符串进行 对比判断
    if (multi_select == more_sure) {
      _t.data.selected_true.push(_t.data.test[index].id)
      _t.data.all_answer_id.push(_t.data.test[index].id)
      _t.data.selected_all.push('1')
    } else {
      _t.data.selected_false.push(_t.data.test[index].id)
      _t.data.all_answer_id.push(_t.data.test[index].id)
      _t.data.selected_all.push('0')
    }
    _t.setData({
      selected_all: _t.data.selected_all,
      all_answer_id: _t.data.all_answer_id,
      selected_true: _t.data.selected_true,
      selected_false: _t.data.selected_false
    })
  },

  // 结束本次考试
  endTheTest() {
    let _t = this
    let t = _t.data

    /*
     *  category_id ：科目id（一级分类）
     *  type_id ：知识点id（二级分类）
     *  minute ：用时分钟
     *  question_number ：题目总数
     *  right_question ：正确数量
     *  考试结束
     */
    let c_id = t.category_id
    let t_id = t.id
    let min = t.remainTime
    let q_num = t.selected_all
    let r_ques = t.selected_true
    let f_ques = t.selected_false
    let t_type = t.t_type
    let all_answer_id = t.all_answer_id


    wx.redirectTo({
      url: '/xc_train/pages/online/test_end/test_end?q_num=' + q_num + '&r_ques=' + r_ques + '&min=' + min + '&t_id=' + t_id + '&c_id=' + c_id + '&t_type=' + t_type + '&f_ques=' + f_ques + '&all_q=' + all_answer_id
    })





    _t.setData({
      timeFlag: false
    })



    // let c_id = t.category_id
    // let t_id = t.id
    // let min = t.remainTime
    // let q_num = t.selected_all
    // let r_ques = t.selected_true
    // let f_ques = t.selected_false
    // let t_type = t.t_type
    // let all_answer_id = t.all_answer_id
    // app.util.request({
    //   url: 'entry/wxapp/examFinish',
    //   data: {
    //     category_id: c_id,
    //     type_id: t_id,
    //     minute: min,
    //     question_number: q_num,
    //     right_question: r_ques
    //   },
    //   success: function (a) {
    //     console.log(a)
    //   },
    //   complete: function (res) {
    //     _t.setData({
    //       timeFlag: false
    //     })
    //   }
    // })



  },
  // 题目
  // startTest(name, id, type, _t) {
  //   type == 1 ? (name = 'category') : (name = 'type')
  //   var startTest = []
  //   var analysis = []
  //   app.util.request({
  //     url: 'entry/wxapp/doExam',
  //     data: {
  //       name: name,
  //       cid: id
  //     },
  //     success: function(a) {
  //       console.log(a)
  //       let data = a.data.data
  //       console.log(data)
  //       for (var i = 0; i < data.length; i++) {
  //         data[i].answer_option = JSON.parse(data[i].answer_option);
  //         data[i].correct = data[i].correct.split(',')

  //         // 选项数据
  //         let answer_option = []
  //         for (var v = 0; v < data[i].answer_option.length; v++) {
  //           answer_option.push({
  //             name: data[i].answer_option[v],
  //             active: false
  //           })
  //         }
  //         data[i].answer_option = answer_option;

  //         // 答案数据
  //         for (var k = 0; k < data[i].correct.length; k++) {
  //           data[i].correct[k] = Number(data[i].correct[k]) + 1
  //         }
  //         // 数据 定义
  //         startTest.push(data[i].subject)
  //         // 讲解 定义
  //         analysis.push(data[i].analysis)

  //         WxParse.wxParse('explain' + i, 'html', data[i].analysis, _t); //讲解
  //         WxParse.wxParse('subject' + i, 'html', data[i].subject, _t); //题目
  //         if (i === data.length - 1) {
  //           WxParse.wxParseTemArray("analysis", 'explain', data.length, _t) //讲解
  //           WxParse.wxParseTemArray("startTest", 'subject', data.length, _t) //题目
  //         }

  //       }
  //       data = data
  //       _t.setData({
  //         test: data
  //       })
  //     }
  //   })
  // },
  startTest(id,_t) {
    var startTest = []
    var analysis = []
    app.util.request({
      url: 'entry/wxapp/Questions',
      data: {
        id: id
      },
      success: function (a) {
        console.log(a)
        let data = a.data.data
        console.log(data)
        for (var i = 0; i < data.length; i++) {
          data[i].answer_option = JSON.parse(data[i].answer_option);
          data[i].correct = data[i].correct.split(',')

          // 选项数据
          let answer_option = []
          for (var v = 0; v < data[i].answer_option.length; v++) {
            answer_option.push({
              name: data[i].answer_option[v],
              active: false
            })
          }
          data[i].answer_option = answer_option;

          // 答案数据
          for (var k = 0; k < data[i].correct.length; k++) {
            data[i].correct[k] = Number(data[i].correct[k]) + 1
          }
          // 数据 定义
          startTest.push(data[i].subject)
          // 讲解 定义
          analysis.push(data[i].analysis)

          WxParse.wxParse('explain' + i, 'html', data[i].analysis, _t); //讲解
          WxParse.wxParse('subject' + i, 'html', data[i].subject, _t); //题目
          if (i === data.length - 1) {
            WxParse.wxParseTemArray("analysis", 'explain', data.length, _t) //讲解
            WxParse.wxParseTemArray("startTest", 'subject', data.length, _t) //题目
          }

        }
        data = data
        _t.setData({
          test: data
        })
      }
    })
  },
  // 收藏 || 取消收藏 题目
  collection(e) {
    console.log(e.currentTarget.dataset.sid)
    let _t = this
    let sid_index = e.currentTarget.dataset.sid
    let sid = _t.data.test[sid_index].id
    let openid = _t.data.users.openid

    app.util.request({
      url: 'entry/wxapp/questionCollect',
      data: {
        sid: sid,
        openid: openid
      },
      success: function(a) {
        console.log(a)
        console.log("=///////////////////////////////////////////////////////")
        wx.showToast({
          title: a.data.message,
          icon: 'none',
          duration: 1500,
        })
      }
    })

  },
  // 获取用户信息
  haveGetUser(_t) {

    console.log(wx.getStorageSync("users"))
    _t.setData({
      users: wx.getStorageSync("users")
    })
  },
  onLoad: function(w) {
    let _t = this

    console.log(_t.data.selected_all + '//全部答案 对错 展示')
    console.log(_t.data.all_answer_id + '//全部答案 的 id')
    console.log(_t.data.selected_true + '//统计正确答案个数')
    console.log(_t.data.selected_false + '//统计错误答案个数')
    console.log("============================================================================onload")

    wx.setNavigationBarTitle({
      title: w.name
    })
    // 获取手机屏幕高度
    let winh = wx.getSystemInfoSync().windowHeight
    // 倒计时
    let list = [{
      remainTime: w.min * 60 * 1000
      // remainTime: 3600
    }];
    this.setData({
      listData: list,
      winh: winh,
      type: w.type,
      t_type: w.t,
      category_id: w.category_id,
      id: w.id,

    });
    //_t.startTest(w.name, w.id, w.t, _t)
    _t.startTest(w.id,_t)
    _t.haveGetUser(_t)
    if (w.type == 1 || w.type == 2) {
      return
    }
    _t.setCountDown()
  },

  onReady: function() {

  },
  onShow: function() {

  },
  onHide: function() {

  },
  onUnload: function() {

  },
  onPullDownRefresh: function() {

  },
  onReachBottom: function() {

  },
  onShareAppMessage: function() {

  },
  // 倒计时
  setCountDown: function() {
    let time = 100;
    let {
      listData
    } = this.data;
    let list = listData.map((v, i) => {
      if (v.remainTime <= 0) {
        v.remainTime = 0;
      }
      let formatTime = this.getFormat(v.remainTime);
      v.remainTime -= time;
      v.countDown = `${formatTime.hh}:${formatTime.mm}:${formatTime.ss}.${parseInt(formatTime.ms / time)}`;

      return v;
    })
    this.setData({
      listData: list
    });
    // 当事件清零的时候 自动结束考试
    if (list[0].countDown == '00:00:00.0' || this.data.timeFlag == false) {
      return
    }
    setTimeout(this.setCountDown, time);
  },

  // 倒计时
  getFormat: function(msec) {
    let ss = parseInt(msec / 1000);
    let ms = parseInt(msec % 1000);
    let mm = 0;
    let hh = 0;
    if (ss > 60) {
      mm = parseInt(ss / 60);
      ss = parseInt(ss % 60);
      if (mm > 60) {
        hh = parseInt(mm / 60);
        mm = parseInt(mm % 60);
      }
    }
    ss = ss > 9 ? ss : `0${ss}`;
    mm = mm > 9 ? mm : `0${mm}`;
    hh = hh > 9 ? hh : `0${hh}`;


    return {
      ms,
      ss,
      mm,
      hh
    };
  }
})